<template>
  <div>
    <div v-if="editing">
      <el-button @click="editing = false" type="primary">保存</el-button>
      <el-button @click="addOrgNode">添加节点</el-button>
      <el-button @click="editOrgNode">编辑节点</el-button>
      <el-button @click="removeOrgNode">删除节点</el-button>
    </div>
    <div v-else>
      <el-button @click="editing = true">编辑沙盘</el-button>
      <el-button @click="exportImg">导出图片</el-button>
    </div>
    <div id="container" style="height: 500px">
      <ZmTreeOrg :data="orgData" center :horizontal="false" :collapsable="true" :draggable="true"
                 :labelStyle="labelStyle"
                 :toolBar="false" :define-menus="[]" :only-one-node="false" :scalable="false" :click-delay="0"
                 :clone-node-drag="false" @on-node-click="nodeClick">
        <template slot-scope="{node}">
          <div class="tree-org-node__text node-label" :class="node.root ? '' : 'vertical'" style="letter-spacing: 4px">
            {{ node.label }}
          </div>
        </template>
        <template v-slot:expand="{node}">
          <div>{{ node.children.length }}</div>
        </template>
      </ZmTreeOrg>
    </div>
  </div>
</template>

<script>
import domtoimage from 'dom-to-image';

export default {
  name: "OrgTree",
  data() {
    return {
      orgData: {
        "id": 1, "label": "xxx科技有限公司",
        "children": [
          {
            "id": 2, "pid": 1, "label": "产品研发部",
            expand: true,
            "children": [
              {"id": 6, "pid": 2, "label": "节点1"},
              {"id": 8, "pid": 2, "label": "禁止拖拽节点", "noDragging": true},
              {"id": 10, "pid": 2, "label": "测试"}
            ]
          },
          {
            "id": 3, "pid": 1, "label": "客服部",
            expand: true,
            "children": [
              {"id": 11, "pid": 3, "label": "客服一部"},
              {"id": 12, "pid": 3, "label": "客服二部"}
            ]
          },
          {"id": 4, "pid": 1, "label": "业务部", expand: true,}
        ],
        expand: true
      },
      selectedOrgId: '',
      selectedOrgName: '',
      labelStyle: {
        background: '#fff',
        color: '#5e6d82',
      },
      editing: false
    }
  },
  methods: {
    nodeClick(e, node) {
      this.selectedOrgId = node.id
      this.selectedOrgName = node.label
      const parents = document.querySelectorAll('.tree-org-node__inner')
      parents.forEach(ele => {
        ele.style.outline = ''
      })
      e.target.parentNode.style.outline = '1px solid #3b82f6'
    },
    addOrgNode() {
      if (this.selectedOrgId === '') {
        this.$message.warning('请先选择组织机构')
        return
      }
      let data = [this.orgData]
      const addNode = (array) => {
        let json = {
          id: String(new Date().getTime()),
          pid: this.selectedOrgId,
          label: '新建节点',
          expand: true,
          children: [],
          newNode: true,
          focused: true
        }
        array.map(item => {
          if (item.id === this.selectedOrgId) {
            item['expand'] = true
            if (item.children) {
              item.children.push(json)
            } else {
              this.$set(item, "children", [json]);
            }
          } else {
            if (item.children) addNode(item.children)
          }
        })
      }
      addNode(data)
      this.orgData = data[0]
    },
    editOrgNode() {
      if (this.selectedOrgId === '') {
        this.$message.warning('请先选择组织机构')
        return
      }
      let data = [this.orgData]
      const editNode = (array) => {
        array.map(item => {
          if (item.id === this.selectedOrgId) {
            this.$set(item, "focused", true);
          } else {
            if (item.children) editNode(item.children)
          }
        })
      }
      editNode(data)
    },
    removeOrgNode() {
      if (this.selectedOrgId === '') {
        this.$message.warning('请先选择组织机构')
        return
      }
      this.$confirm(`此操作将永久删除“${this.selectedOrgName}”节点, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = [this.orgData]
        const removeNode = (array) => {
          array.map((item, index) => {
            if (item.id === this.selectedOrgId) {
              if (!item.pid) {
                this.$message.error('根节点不允许删除')
              } else {
                array.splice(index, 1)
              }
            } else {
              if (item.children) removeNode(item.children)
            }
          })
        }
        removeNode(data)
        this.orgData = data[0]
      }).catch(() => {
      })
    },
    exportImg() {
      let node = document.querySelector('#container')
      domtoimage.toPng(node, {width: window.screen.width, height: window.screen.height}).then(url => {
        let a = document.createElement('a')
        a.href = url
        a.download = 'org.png'
        a.click()
      })
    },
  }
}
</script>

<style scoped lang="less">
.vertical {
  writing-mode: vertical-rl;
  text-orientation: upright;
}

/deep/ .tree-org-node__textarea {
  resize: none;
  border-radius: 2px;
  padding-top: 5px;
  padding-left: 5px;
}

/deep/ .zm-tree-org .zoom-container.is-center {
  align-items: center;
}
</style>
